<?php

namespace App\Imports;

use App\Models\User;
use App\Rules\IdCard;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class UserImport implements ToCollection, WithStartRow, WithChunkReading, WithBatchInserts, WithValidation
{
    use Importable;

    protected $start = 2;

    protected $chunk = 100;

    protected $batch = 100;

    /**
     * @param Collection $collection
     * @return mixed
     */
    public function collection(Collection $collection)
    {
        $users = [];

        $timer = Carbon::now()->toDateTimeString();

        foreach ($collection as $key => $item) {
            $users[$key]['name'] = $item[0];
            $users[$key]['username'] = $item[1];
            $users[$key]['email'] = $item[2];
            $users[$key]['phone'] = $item[3];
            $users[$key]['id_card'] = $item[4];
            $users[$key]['status'] = 1;
            $users[$key]['password'] = bcrypt(123123);
            $users[$key]['created_at'] = $timer;
            $users[$key]['updated_at'] = $timer;
        }

        User::insert($users);
    }

    /**
     * 导入数据验证
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            '0' => 'required|string|min:2|max:22',
            '1' => 'required|string|min:2|max:22|unique:users,username',
            '2' => 'required|email|unique:users,email',
            '3' => ['sometimes', 'nullable', 'regex:/^1(?:(?:(?:3|5|7|8)[0-9])|47|6[89]|99)\d{8}$/'],
            '4' => ['sometimes', 'nullable', new IdCard(), 'unique:users,id_card'],
        ];
    }

    /**
     * 返回信息提示
     *
     * @return string[]
     */
    public function customValidationAttributes(): array
    {
        return [
            '0' => '姓名',
            '1' => '登录名',
            '2' => '邮箱',
            '3' => '手机号',
            '4' => '身份证',
        ];
    }

    /**
     * 从第几行开始
     *
     * @return int
     */
    public function startRow(): int
    {
        return $this->start;
    }

    /**
     * @return int
     */
    public function chunkSize(): int
    {
        return $this->chunk;
    }

    /**
     * @return int
     */
    public function batchSize(): int
    {
        return $this->batch;
    }
}
